<template>
  <div class="update-name">
    <van-nav-bar
      title="设置昵称"
      left-text="取消"
      @click-left="$emit('close')"
      @click-right="onConfirm"
      right-text="完成"
    />
    <div class="field-wrap">
      <van-field
        v-model.trim="localName"
        rows="2"
        autosize
        type="textarea"
        maxlength="50"
        placeholder="请输入昵称"
        show-word-limit
      />
    </div>
  </div>
</template>

<script>
import { updateUserProfile } from '@/api/user'
export default {
  name: 'UpdateName',
  props: {
    value: {
      // 用户姓名
      type: String,
      required: true
    }
  },
  data () {
    return {
      localName: this.value // 因为value是父亲传来的，不能直接修改，如果上面绑定value直接修改就会报错，所以将 message 初始化的值设置为 value，用message来进行双向绑定
    }
  },
  methods: {
    async onConfirm () {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 持续展示
      })
      try {
        if (!this.localName) {
          // if (this.localName.trim().length === 0) {
          this.$toast('昵称不能为空')
          return
        }
        // console.log(this.localName.length)
        await updateUserProfile({
          name: this.localName
        })
        this.$emit('input', this.localName)
        this.$emit('close')
        this.$toast.success('更新成功')
      } catch (error) {
        this.$toast.fail('更新失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.update-name {
  .van-popup {
    background-color: #f5f7f9;
  }
  .field-wrap {
    padding: 20px;
  }
}
</style>
